package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.properties.ShopProperties;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private ShopProperties shopProperties;
    public static String URL = "https://api.map.baidu.com/geocoding/v3?";
    public static String URL2 = "https://api.map.baidu.com/direction/v2/driving?";


    /**
     * 用户下单--最终目的，将订单数据存入表中
     *
     * @param dto
     * @return
     */
    @Override
    public OrderSubmitVO addOrder(OrdersSubmitDTO dto) {
        //查询地址表查询收货人
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询用户表，获取用户相关信息
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.queryById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }
        //TODO 在此处优化代码 超出配送范围则禁止配送
        String orderAddress = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        String origin = requestBaiduGetLongitudeAndLatitude(shopProperties.getAddres());
        String destination = requestBaiduGetLongitudeAndLatitude(orderAddress);
        Long distance = requestGetdistence(origin, destination, orderAddress);
        if (distance > 5000) {
            throw new AddressBookBusinessException(MessageConstant.BEYOND_DELIVERY_RANGE);
        }

        //查询购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.list(userId);
        if (cartList == null || cartList.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 1.构造订单数据
        Orders orders = new Orders();
        // 2.插入订单数据到orders表中
        BeanUtils.copyProperties(dto, orders);
        orders.setNumber(System.currentTimeMillis() + "");
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());//查询地址表查询收货人手机号
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());//收货人//查询地址表查询收货人
        orders.setUserName(user.getName());//根据当前登录用户id查询当前下单的人名
        ordersMapper.insert(orders);
        // 3.构造订单明细列表数据--从购物车获取订单明细数据
        List<OrderDetail> orderDetails = new ArrayList<>();//查询购物车放入集合
        //循环遍历购物车明细数据，存入oreder_detail中
        cartList.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });
        //批量插入订单明细数据        // 4.将订单明细列表数据批量插入到order_detail表中
        orderDetailMapper.insertBatch(orderDetails);
        // 5.清空购物车数据（自己名下的）
        shoppingCartMapper.delete(ShoppingCart.builder().id(userId).build());
        // 6.构造vo对象并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    private Long requestGetdistence(String origin, String destination, String orderAddress) {
        Map params = new LinkedHashMap<String, String>();
        params.put("origin", origin);
        params.put("destination", destination);
        params.put("ak", shopProperties.getAK());
        String result = HttpClientUtil.doGet(URL2, params);
        JSONObject resultJsonObject = JSONObject.parseObject(result);
        int status = (int) resultJsonObject.get("status");
        if (status != 0) {
            throw new AddressBookBusinessException(resultJsonObject.get("message").toString());
        }
        JSONObject jsonObject = resultJsonObject.getJSONObject("result").getJSONArray("routes").getJSONObject(0);

        Long distance = Long.valueOf(jsonObject.get("distance").toString());
        return distance;
    }

    /**
     * 获取地址的坐标
     * @param address
     * @return
     */
    private String requestBaiduGetLongitudeAndLatitude(String address) {
        Map params = new LinkedHashMap<String, String>();
        params.put("address", address);
        params.put("output", "json");
        params.put("ak", shopProperties.getAK());
        String result = HttpClientUtil.doGet(URL, params);
        JSONObject resultJsonObject = JSONObject.parseObject(result);
        int status = (int) resultJsonObject.get("status");
        if (status != 0) {
            throw new AddressBookBusinessException(resultJsonObject.get("message").toString());
        }
        JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("result").getJSONObject("location");
        String  lng = jsonObject.get("lng").toString();
        String lat = jsonObject.get("lat").toString();
        return lat+"," + lng;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
/*        Long userId = BaseContext.getCurrentId();
        User user = userMapper.queryById(userId);*/
/*
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;*/
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //代码优化：通过websocket实现下单提醒
        Map map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号:" + ordersDB.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO queryOrderDetailById(Long id) {
        OrderVO orderVO = ordersMapper.queryOrderDetailById(id);
        orderVO.setOrderDetailList(orderDetailMapper.queryOrderDetailById(id));
        return orderVO;
    }

    @Override
    public PageResult queryHistoryOrders(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        dto.setUserId(BaseContext.getCurrentId());
        Page<OrderVO> page = ordersMapper.queryOrders(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancelById(Long id) {
        Orders order = Orders.builder().id(id).status(Orders.CANCELLED).build();
        ordersMapper.update(order);
        //执行退款操作
    }

    /**
     * 再来一单
     * @param id 订单id
     */
    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.queryOrderDetailById(id);

        orderDetails.forEach(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setId(null);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        });
    }


    /**
     * 订单搜索
     * @param dto
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrderVO> page = ordersMapper.conditionSearch(dto);
        page.forEach(
                orderVO -> {
                    List<OrderDetail> orderDetails = orderDetailMapper.queryOrderDetailById(orderVO.getId());
                    String dishDetails = orderDetails.stream().map(OrderDetail::getName).collect(Collectors.joining(","));
                    orderVO.setOrderDishes(dishDetails);
                    log.info("dishDetails:{}",dishDetails);
                }
        );
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 接单
     * @param dto
     */
    @Override
    public void confirm(OrdersConfirmDTO dto) {
        Orders orders = Orders.builder().id(dto.getId()).status(Orders.CONFIRMED).build();
        ordersMapper.update(orders);
    }

    /**
     * 拒单
     * @param dto
     */
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto,orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setPayStatus(Orders.REFUND);
        ordersMapper.update(orders);
        //退款
    }

    /**
     * 取消订单
     * @param dto
     */
    @Override
    public void cancel(OrdersCancelDTO dto) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setPayStatus(Orders.REFUND);
        orders.setStatus(Orders.CANCELLED);
        ordersMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliveryById(Long id) {
        Orders orders = Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build();
        ordersMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder().id(id).status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build();
        ordersMapper.update(orders);
    }

    /**
     * 各个状态订单统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Orders orders = new Orders();
        List<Map> numbers = ordersMapper.statistics();
        log.info("map:{}",numbers);
        OrderStatisticsVO vo = new OrderStatisticsVO();
        for (Map number : numbers) {
            int status = (int) number.get("status");
            int count = ((Number) number.get("count(*)")).intValue();
            if (status == Orders.TO_BE_CONFIRMED) {
                vo.setToBeConfirmed(count);
            } else if (status == Orders.CONFIRMED) {
                vo.setConfirmed(count);
            } else {
                vo.setDeliveryInProgress(count);
            }

        }
        return vo;
    }

    /**
     * 催单
     * @param id 订单id
     */
    @Override
    public void reminder(Long id) {
        Map map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
//        map.put("content", "订单);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}